const express = require("express");
const router = express.Router();
const { Course,Category, User } = require("../models");
const { success, failure, NotFoundError } = require("../utils/response");

/**
 * 查询首页数据
 * GET /
 */
router.get("/", async function (req, res, next) {
  try {
    const recommendedCourses = await Course.findAll({
      // attributes：指定返回的字段。例如 exclude 表示排除的字段（如 "CategoryId", "UserId", "content"）
      attributes: {
        exclude: ["categoryId", "userId", "content"],
      },
      // include：用于关联查询
      include: [
        {
          model: Category,
          as: "category",
          attributes: ["id", "name"],
        },
        {
          model: User,
          as: "user",
          attributes: ["id", "username"],
        },
      ],
      // where：用于设置查询的条件
      where: {
        recommended: 1,
      },
      // order：设置查询结果的排序方式
      order:[["id", "desc"]],
      limit:10
    });

    // 人气课程
    const likedCourses = await Course.findAll({
      // attributes
      attributes: {
        exclude: ["CategoryId", "UserId", "content"],
      },
      order:[["likesCount", "desc"],["id", "desc"]],
      limit:10
    })

    success(res, "获取首页查询成功", { recommendedCourses, likedCourses });
  } catch (error) {
    // 如果发生错误，返回错误信息
    failure(res, error);
  }
});

module.exports = router;
